<template>
  <div class="tw-libchart" :style="{height: height, backgroundColor: bgColor}">
    <div v-show="data.length>0"
      class="tw-datasetchart xantvradar" :style="{height: height, width: width}"
      ref="chart">
    </div>

    <tw-lib-nodata v-show="data.length===0" />
  </div>
</template>

<script>
import props from './props'
import chartMixins from '../tw-lib-base/chart/chart'

import AntvDataSet from '@antv/data-set'
import { Chart } from '@antv/g2'

export default {
  name: 'chart-customized-antvradar',

  mixins: [chartMixins],

  props,

  data() {
    return {
      chartantv: null,
      chartType: 'radar'
    }
  },

  methods: {
    init () {
      let vm = this
      this.chartantv = new Chart({
        container: vm.$refs.chart,
        // autoFit: true,
        // width: parseInt(vm.width),
        height: parseInt(vm.height),
        padding: [50, 20, 20 ,20],
        autoFit: true,
      })
      if (vm.data.length > 0) {

        this.setOption()
        this.resize()

        setTimeout(() => {
          this.chartantv.forceFit()
        }, 0)
      }
    },
    setSeries () {
    },

    setOption () {
      let vm = this

      let data = []

      let maxvalue = 0
      // let unit = 0

      // for (let i = 0; i <= this.data.length - 1; i++) {
      //   Object.keys(this.data[i]).forEach((item, index) => {
      //     if (index > 0 && maxvalue <= vm.data[i][item]) {
      //       maxvalue = vm.data[i][item] + 0
      //     }
      //   })
      // }

      let keys = []
      let lists = []
      let items = []
      if (this.data.length > 0) {
        this.legendData.forEach((item, index) => {
          keys.push(item)
          items.push({
            name: item,
            marker: {
              symbol: 'square',
              style:{
                fill: vm.colors[index]
              },
              clickable: false
            }
          })
        })
        // Object.keys(this.data[0]).forEach((item, index) => {
        //   if (index > 1) {
        //     keys.push(item)

        //     items.push({
        //       name: item,
        //       marker: {
        //         symbol: 'square',
        //         style:{
        //           fill: vm.colors[index - 1]
        //         },
        //         clickable: false
        //       }
        //     })
        //   }
        // })
      } else {
        if (this.chartantv) {
          this.chartantv.clear()
        }
        return
      }

      // if (!this.maxValue) {
      maxvalue = 100
      this.data.forEach(item => {
        let tmpitm = { ...item }
        let itm = JSON.parse(JSON.stringify(tmpitm))

        if (item.max === 0) {
          let v = 0
          let k = 0
          for (let i = 0; i < keys.length; i++) {
            if (i === 0) {
              v = parseFloat(itm[keys[0]])
              k = 0
            } else {
              k = v > parseFloat(itm[keys[i]]) ? k : i
              v = v > parseFloat(itm[keys[i]]) ? v : parseFloat(itm[keys[i]])
            }
          }

          for (let i = 0; i < keys.length; i++) {
            if (k === i) {
              itm[keys[i]] = 100
            } else {
              itm[keys[i]] = Math.round(parseFloat(itm[keys[i]]) * 10000 / v) / 100
            }
          }
        } else if (item.max > 0 && item.max !== 100) {
          for (let i = 0; i < keys.length; i++) {
            // itm[keys[i]] = parseFloat(itm[keys[i]])
            if (itm[keys[i]] === item.max) {
              itm[keys[i]] = 100
            } else {
              itm[keys[i]] = Math.round(parseFloat(itm[keys[i]]) * 10000 / parseFloat(item.max)) / 100
            }
          }
        } else {
          for (let i = 0; i < keys.length; i++) {
            itm[keys[i]] = parseFloat(itm[keys[i]])
          }
        }

        data.push({
          ...itm
        })
      })

      // }
      //  else {
      //   maxvalue = parseFloat(this.maxValue)
      //   this.data.forEach((item) => {
      //     let itm = { ...item }
      //     for (let i = 0; i < keys.length; i++) {
      //       itm[keys[i]] = parseFloat(itm[keys[i]])
      //     }
      //     data.push({
      //       ...itm
      //     })
      //   })
      // }

      let { DataView } = AntvDataSet
      let dv = new DataView().source(data)
      dv.transform({
        type: 'fold',
        fields: keys, // 展开字段集
        key: 'user', // key字段
        value: 'score', // value字段
      })
      // if (this.chartantv) {
      //   this.chartantv.destroy()
      //   this.chartantv = null
      //   // let b =document.getElementById('chart').childNodes
      //   // for (let i = 0; i < b.length; i++) {
      //   //   document.getElementById('chart').removeChild(b[i])
      //   // }
      // }
      // let b =document.getElementById('chart').childNodes
      // for (let i = 0; i < b.length; i++) {
      //   document.getElementById('chart').removeChild(b[i])
      // }
      // this.chartantv = new Chart({
      //   container: vm.$refs.chart,
      //   // autoFit: true,
      //   // width: parseInt(vm.width),
      //   height: parseInt(vm.height),
      //   padding: [50, 20, 20 ,20],
      //   autoFit: true,
      // })
      if (this.chartantv) {
        this.chartantv.clear()
      } else {
        return
      }

      if (this.showLegend) {
        this.chartantv.legend({
          position: 'top',
          items: items
        })
      } else {
        this.chartantv.legend(false)
      }

      this.chartantv.data(dv.rows);
      this.chartantv.scale({
        score: {
          min: 0,
          max: maxvalue,
          nice: true,
          tickCount: 5
        }
      })
      this.chartantv.coordinate('polar', {
        radius: 0.8,
      })

      this.chartantv.tooltip({
        shared: true,
        showCrosshairs: false,
        showTitle: true,
        showMarkers: false,
        containerTpl: '<div class="g2-tooltip">' +
          `<div class="g2-tooltip-title">{item}</div>` +
          `<div class="g2-tooltip-list"></div>` + '</div>',
        itemTpl: `
          <li class="g2-tooltip-list-item tooltip-line"><span class="g2-tooltip-marker" style="background-color:{color};"></span><span class="tooltip-cat">{name}:&nbsp;&nbsp;</span><span class="tooltip-number">{value}</span></li>
        `
      })

      this.chartantv.axis('name', {
        line: null,
        tickLine: null,
        label: {
          style: {
            fill: '#000',
            fontSize: 14
          },
          offset: 10,
        },
        grid: {
          line: {
            style: {
              lineDash: null,
            },
          },
        },
      })
      this.chartantv.axis('score', {
        line: null,
        tickLine: null,
        label: {
          style: {
            fillOpacity: 0,
          }
        },
        grid: {
          line: {
            type: 'circle',
            style: {
              lineDash: null,
            },
          },
          alternateColor: ['rgba(250,250,250,0)', 'rgba(200,200,200,0)'],
        },
      })

      this.chartantv
        .line()
        .position('name*score')
        .color('user', vm.colors)
        .size(2);
      this.chartantv
        .point()
        .position('name*score')
        .color('user', vm.colors)
        .shape('circle')
        .size(4)
        .style({
          stroke: '#fff',
          lineWidth: 1,
          fillOpacity: 1,
        });
      // this.chartantv
      //   .area()
      //   .position('name*score')
      //   .color('user')

      this.chartantv.off('tooltip:change')
      this.chartantv.on('tooltip:change', ev => {
        // console.log(ev)
        let evitems = []
        let evtitle = ''
        // 搞不懂，莫名其妙现网字段不见了
        if (ev.items && ev.items.length > 0) {
          evitems = ev.items
          evtitle = ev.title
        } else if (ev.data && ev.data.items && ev.data.items.length > 0) {
          evitems = ev.data.items
          evtitle = ev.data.title
        } else {
          return
        }
        let olditems = []
        evitems.forEach((item, index) => {
          olditems.push({...item})
        })

        // x: 当前鼠标的 x 坐标,
        // y: 当前鼠标的 y 坐标,
        // tooltip: 当前的 tooltip 对象
        // items: 数组对象，当前 tooltip 显示的每条内容
        // title: tooltip 标题
        let idx = data.findIndex(itm => itm.name === evtitle)

        if (idx > -1) {
          let tmpdata = this.data[idx]
          let items = []

          let a = []
          evitems.forEach((item, index) => {
            let name = olditems[index].name
            if (a.length > 0 && a.includes(name)) {
              evitems.pop()
            } else {
              a.push(name)
              let itm = {...item}
              if (vm.tooltipData[idx][0]) {
                item.name = name + vm.tooltipData[idx][0]
              }
              if (vm.tooltipData[idx][index + 1]) {
                item.value = tmpdata[name] + vm.tooltipData[idx][index + 1]
              }
            }
          })

          let itemdata = vm.data.find(itm => itm.name === evtitle)
          Object.keys(itemdata).forEach((item, index) => {
            if (!vm.legendData.includes(item) && item !== 'name' && item !== 'max') {
              evitems.push({
                marker: true,
                color: vm.colors[index],
                name: item,
                value: itemdata[item]
              })
            }
          })
        }
      })

      this.chartantv.render()
      this.resize()
    },

    handleclick (params) {

    },

    resize () {
      let width = this.$refs.chart.clientWidth || parseInt(this.$el.offsetWidth) || parseInt(this.$ui.el.innerWidth(this.$el.parentElement))
      let height = parseInt(this.height) || parseInt(this.$el.offsetHeight)
      this.chartantv.changeSize(width, height)
      // this.chartantv.height = height
      // this.chartantv.forceFit()
    },

  },

  beforeDestroy () {
    window.removeEventListener('resize', this.resize)

    if (this.chartantv) {
      this.chartantv.destroy()
      this.chartantv = null
    }
  },

  watch: {
    width () {
      this.resize()
    },
    height () {
      this.resize()
    },
    showLegend () {
      this.setOption()
    },
    colors: {
      deep: true,
      handler () {
        this.setOption()
      }
    },
    data: {
      deep: true,
      handler () {
        this.setOption()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
